package com.github.wxiaoqi.security.admin.rest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.wxiaoqi.security.admin.biz.DeptBiz;
import com.github.wxiaoqi.security.admin.constant.AdminCommonConstant;
import com.github.wxiaoqi.security.admin.entity.Dept;
import com.github.wxiaoqi.security.admin.vo.DeptTree;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.TreeUtil;
import com.mysql.fabric.xmlrpc.base.Array;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 *　@author bolei
 *　@date Apr 8, 2018
　*　@description 
**/

@RestController
@RequestMapping("dept")
public class DeptController extends BaseController<DeptBiz, Dept> {
	
    @Autowired
    private DeptBiz deptBiz;
	
	@RequestMapping(value = "/tree", method = RequestMethod.GET)
    @ResponseBody
    public List<DeptTree> getTree(@RequestParam Map<String, Object> param) {
		String title = (String) param.get("title");
		String userType = (String) param.get("userType");
		String platformId = (String) param.get("platformId");
		Integer parentId = AdminCommonConstant.ROOT;
		
        Example example = new Example(Dept.class);
        Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(title)) {
        	criteria.andLike("title", "%" + title + "%");
        }
        List<Dept> list = new ArrayList<Dept>();
        Dept deptOther = null;
        try {
			if("2".equals(userType)){
				Dept dept = new Dept();
				dept.setParentId(1);
				dept.setPlatformId(Long.valueOf(platformId));
				deptOther = deptBiz.selectOne(dept);
				parentId = deptOther.getParentId();
				criteria.andEqualTo("parentId", deptOther.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
        list = baseBiz.selectByExample(example);
        if(deptOther != null){
        	list.add(deptOther);
        }
        //根据用户
        return getDeptTree(list, parentId);
    }
	
	private List<DeptTree> getDeptTree(List<Dept> depts,int root) {
        List<DeptTree> trees = new ArrayList<DeptTree>();
        DeptTree node = null;
        for (Dept dept : depts) {
            node = new DeptTree();
            BeanUtils.copyProperties(dept, node);
            node.setLabel(dept.getName());
            trees.add(node);
        }
        return TreeUtil.bulid(trees,root) ;
    }

}
